<template>
    <div class="common-header">
        <h3 class="header-title" @click="goToIndex">{{ title }}</h3>
        <div class="user-info">
            <el-switch class="theme-toggle" v-model="darkMode" @change="toggleDarkMode" active-color="#2c3e50"
                inactive-color="#409EFF" active-text="🌛" inactive-text="🌞" />
            <div class="avatar-container">
                <el-badge is-dot :hidden="unreadCount <= 0" :max="99">
                    <div class="avatar">
                        {{ userInitial }}
                    </div>
                </el-badge>
                <div class="avatar-menu" v-show="username === '游客' ? fasle : true">
                    <div class="menu-item" @click="goToMessage">个人信息</div>
                    <el-badge :value="unreadCount" :max="99" >
                        <div class="menu-item" @click="goToPrivate">
                            <span>我的消息</span>
                        </div>
                    </el-badge>
                    <div class="menu-item" @click="handleLogout">退出登录</div>
                </div>
                <div class="avatar-menu" v-show="username === '游客' ? true : false">
                    <div class="menu-item" @click="goToLogin">登录</div>
                    <div class="menu-item" @click="goToRegister">注册</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    props: {
        title: {
            type: String,
            default: '聊天室'
        }
    },
    computed: {
        username() {
            try {
                const user = JSON.parse(localStorage.getItem('user') || '{}')
                return user.username || '游客'
            } catch {
                return '游客'
            }
        },
        userInitial() {
            return this.username.charAt(0).toUpperCase()
        }
    },
    data() {
        return {
            darkMode: false,
            pollingInterval: 5000, // 轮询间隔时间（毫秒）
            pollingTimer: null, // 用于存储定时器的引用
            unreadCount: 0 // 未读消息数量
        }
    },
    created() {
        this.$bus.$on('token-expired', this.cleanupTimers)
        this.darkMode = localStorage.getItem('darkMode') === 'true'
        this.toggleDarkMode()
        this.startPolling()
    },
    beforeDestroy() {
        this.$bus.$off('token-expired', this.cleanupTimers)
        this.stopPolling()
        this.cleanupTimers()
    },
    methods: {
        cleanupTimers() {
            // 清除所有定时器
            if (this.timer) {
            clearInterval(this.timer)
            this.timer = null
            }
        },
        goToIndex() {
            this.$router.push('/index')
        },
        toggleDarkMode() {
            localStorage.setItem('darkMode', this.darkMode)
            document.documentElement.classList.toggle('dark-mode', this.darkMode)
        },
        goToMessage() {
            this.$router.push('/message')
        },
        goToPrivate() {
            try {
                const chatList = JSON.parse(localStorage.getItem('chatList')) || [];
                this.$router.push('/chat/private/' + chatList[0].username);
            } catch (error) {
                console.error('获取未读消息列表失败:', error);
                this.$message.error('获取未读消息失败');
            }
        },
        async handleLogout() {
            try {
                await this.$axios.post('/user/logout').then(response => {
                    if (response.data.code === 200) {
                        this.$message.success('退出登录成功') 
                    }
                })
                localStorage.removeItem('user')
                localStorage.removeItem('unreadList')
                localStorage.removeItem('unreadCount')
                localStorage.removeItem('messageList')
                this.$router.push('/login')
            } catch (error) {
                console.error('退出登录失败:', error)
            }
        },
        goToLogin() {
            this.$router.push('/login')
        },
        goToRegister() {
            this.$router.push('/register')
        },
        startPolling() {
            this.pollingTimer = setInterval(() => {
                this.fetchUnreadCount()
            }, this.pollingInterval)
        },
        stopPolling() {
            if (this.pollingTimer) {
                clearInterval(this.pollingTimer)
                this.pollingTimer = null
            }
        },
        async fetchUnreadCount() {
            const username = JSON.parse(localStorage.getItem('user')).username
            if (!username) {
                this.stopPolling()
                return
            }
            try {
               this.$axios.post('/message/getUnreadCount', {
                currentUsername: username
               }).then(response => {
                    if (response.data.code === 200) {
                        localStorage.setItem('unreadCount', response.data.data)
                        this.unreadCount = response.data.data
                    }
                }) 
            } catch (error) {
                console.error('获取未读消息数量失败:', error)
            }
        }
    }
}
</script>

<style scoped>
@import '@/assets/css/components/common-header.css';
</style>
